package cn.lili.modules.member.serviceimpl;

import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.RedPackUserHistory;
import cn.lili.modules.member.mapper.RedPackUserHistoryMapper;
import cn.lili.modules.member.service.RedPackUserHistoryService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Slf4j
public class RedPackUserHistoryServiceImpl extends ServiceImpl<RedPackUserHistoryMapper, RedPackUserHistory>
        implements RedPackUserHistoryService {

    /**
     * 分页获取用户红包变更明细
     * @param page
     * @return
     */
    @Override
    public Map<Object, Object> getByPage (PageVO page) {
        Map<Object, Object> resultMap = new HashMap<>();
        LambdaQueryWrapper<RedPackUserHistory> queryWrapper = new LambdaQueryWrapper<>();
        if (!SceneEnums.MANAGER.name().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name())) {
            queryWrapper.eq(RedPackUserHistory::getMemberId, UserContext.getCurrentId());
        }
        queryWrapper.orderByDesc(RedPackUserHistory::getCreateTime);
        Page<RedPackUserHistory> p = this.baseMapper.selectPage(PageUtil.initPage(page), queryWrapper);
        if (!p.getRecords().isEmpty()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            p.getRecords().forEach(redPackUserHistory -> redPackUserHistory.setCreateDate(sdf.format(redPackUserHistory.getCreateTime())));
            Map<String, List<RedPackUserHistory>> map = p.getRecords().stream().collect(Collectors.groupingBy(RedPackUserHistory::getCreateDate));
            resultMap.put("data", map);
        }else {
            resultMap.put("data", new HashMap<>());
        }
        resultMap.put("count", p.getTotal());

        log.info("分页获取用户红包变更明细:{}", resultMap);
        return resultMap;
    }


    /**
     * 分页获取用户红包变更明细
     * @return
     */
    @Override
    public Page<RedPackUserHistory> getByPage (String userId,PageVO pageVO) {
        LambdaQueryWrapper<RedPackUserHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(userId), RedPackUserHistory::getMemberId, userId);
        queryWrapper.orderByDesc(RedPackUserHistory::getCreateTime);
        return this.baseMapper.selectPage(PageUtil.initPage(pageVO), queryWrapper);
    }
}
